<template>
  <div class="user-management">
    <h2 class="title1" style="margin-bottom: 20px;">
      <el-icon :size="25">
        <Setting />
      </el-icon> 情绪记录
    </h2>

    <!-- 查询区域 -->
    <el-card class="box-card query-card" shadow="never" style="margin-bottom: 20px">
      <template #header>
        <div class="card-header">
          <span>操作项</span>
        </div>
      </template>
      <div class="filter-section">
        <div class="filter-item">
          <span>记录ID：</span>
          <el-input v-model="filters.recordId" placeholder="请输入记录ID" style="width: 200px" />
        </div>
        <div class="filter-item">
          <span>上传时间：</span>
          <el-date-picker v-model="filters.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 300px; margin-left: 5px" />
        </div>
        <div class="filter-item">
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="success" plain @click="reset">重置</el-button>
        </div>
        <div class="action-buttons">
          <el-button type="danger" plain @click="batchDelete">批量删除</el-button>
        </div>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="table-header">
          <div class="card-header">
            <span>数据列表</span>
          </div>
          <div class="action-buttons">
            <el-button type="primary" plain @click="exportToExcel">导出</el-button>
          </div>
        </div>
      </template>
      <div class="data-table-scroll">
        <el-table :data="displayedRecords" border style="width: 100%; margin-top: 20px;"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="60"></el-table-column>
          <el-table-column label="序号" align="center" width="100">
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="id" label="记录ID" align="center" width="140"></el-table-column>
          <el-table-column prop="name" label="用户名" align="center" width="140"></el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" align="center"></el-table-column>
          <el-table-column prop="image" label="上传图片" align="center" width="300">
            <template #default="scope">
              <div class="single-line-img">
                <span v-if="scope.row.image"
                  style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block;">
                  {{ scope.row.image }}
                </span>
                <span v-else style="color:#bbb;">无</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template #default="scope">
              <el-button type="primary" size="middle" @click="viewRecord(scope.row)">查看</el-button>
              <el-button type="danger" size="middle" @click="deleteRecord(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background layout="total, sizes, prev, pager, next" :total="filteredRecords.length"
          :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看弹窗 -->
    <el-dialog v-model="dialogVisible" title="记录信息" width="620px" top="8vh" :close-on-click-modal="false" center>
      <div class="emo-detail-content">
        <div class="emo-detail-row">
          <span class="emo-detail-label">记录ID：</span>
          <span class="emo-detail-value">{{ currentRecord?.id }}</span>
        </div>
        <div class="emo-detail-row">
          <span class="emo-detail-label">上传图片：</span>
          <span class="emo-detail-value">
            <div class="emo-img-box">
              <img v-if="currentRecord?.image" :src="currentRecord.image" alt="图片" />
              <span v-else style="color:#bbb;">无</span>
            </div>
          </span>
        </div>
        <div class="emo-detail-row emo-detail-report">
          <span class="emo-detail-label" style="align-self: flex-start;">情绪分析报告：</span>
          <span class="emo-detail-value">
            <div v-if="currentRecord?.emotionReport?.analyze_content" class="emo-rich-content"
              v-html="currentRecord.emotionReport.analyze_content"></div>
            <pre v-else class="emo-json">{{ formattedReport }}</pre>
          </span>
        </div>
        <div class="emo-detail-btn">
          <el-button type="primary" @click="dialogVisible = false">确认/关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import * as XLSX from 'xlsx'

const md = new MarkdownIt()

// 数据
const records = ref([])

// 获取记录数据
const fetchRecords = async () => {
  try {
    const response = await axios.get('http://localhost:8181/uploadRecord/getRecordList', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      records.value = response.data.data.map(item => ({
        id: item.recordId,
        name: item.name,
        userId: item.userId,
        image: item.fileUrl,
        fileType: item.fileType,
        uploadTime: item.uploadTime ? item.uploadTime.slice(0, 10) : '',
        emotion_type: item.emotionType || '未检测'
      }))
      ElMessage.success('获取记录成功')
    } else {
      ElMessage.error(response.data.message || '获取记录失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}
// 筛选条件
const filters = reactive({
  recordId: '',
  dateRange: []
})

// 导出记录
const exportToExcel = () => {
  // 构造表头和数据
  const data = [
    ['序号', '记录ID', '用户名', '上传时间', '上传图片', '情绪类型'],
    ...filteredRecords.value.map((row, idx) => [
      idx + 1,
      row.id,
      row.name,
      row.uploadTime,
      row.image,
      row.emotion_type
    ])
  ]
  // 创建工作表和工作簿
  const worksheet = XLSX.utils.aoa_to_sheet(data)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '情绪记录')
  // 导出
  XLSX.writeFile(workbook, '情绪记录.xlsx').then(
    ElMessage.success('导出成功')
  )
}

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 过滤后的数据
const filteredRecords = computed(() => {
  return records.value.filter((record) => {
    // 记录ID筛选
    const matchId = filters.recordId ? String(record.id).includes(filters.recordId) : true
    // 上传时间筛选
    let matchDate = true
    if (filters.dateRange && filters.dateRange.length === 2) {
      // 转换为字符串格式
      const start = filters.dateRange[0]
        ? `${filters.dateRange[0].getFullYear()}-${(filters.dateRange[0].getMonth() + 1).toString().padStart(2, '0')}-${filters.dateRange[0].getDate().toString().padStart(2, '0')}`
        : ''
      const end = filters.dateRange[1]
        ? `${filters.dateRange[1].getFullYear()}-${(filters.dateRange[1].getMonth() + 1).toString().padStart(2, '0')}-${filters.dateRange[1].getDate().toString().padStart(2, '0')}`
        : ''
      matchDate = record.uploadTime >= start && record.uploadTime <= end
    }
    return matchId && matchDate
  })
})

// 当前页显示的数据
const displayedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRecords.value.slice(start, end)
})

// 查询功能
const search = () => {
  currentPage.value = 1
}

// 重置功能
const reset = () => {
  filters.recordId = ''
  filters.dateRange = []
  currentPage.value = 1
}

// 分页
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

// 批量删除
const selectedRecords = ref([])
const handleSelectionChange = (selection) => {
  selectedRecords.value = selection
}
const batchDelete = () => {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  ElMessageBox.confirm('确定要删除选中的记录吗？', '提示', {
    type: 'warning'
  }).then(() => {
    records.value = records.value.filter((record) => !selectedRecords.value.includes(record))
    ElMessage.success('删除成功')
  })
}

// 查看
const viewRecord = async (row) => {
  currentRecord.value = row
  formattedReport.value = '加载中...'
  dialogVisible.value = true
  try {
    const response = await axios.get(`http://localhost:8181/EmoAnalyze/getByRDId/${row.id}`, {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200 && Array.isArray(response.data.data) && response.data.data.length > 0) {
      // 提取 analyze_content
      const report = response.data.data[0]
      currentRecord.value.emotionReport = report
      let content = report.analyze_content
      if (content && typeof content === 'string') {
        // 处理 Markdown 格式
        content = content.replace(/^<answer>\s*/i, '').replace(/\s*<\/answer>$/i, '')
        // markdown转html
        currentRecord.value.emotionReport.analyze_content = md.render(content)
      }
      if (row.emotionReport) {
        formattedReport.value = JSON.stringify(row.emotionReport, null, 2)
      } else {
        formattedReport.value = '暂无分析报告'
      }
      ElMessage.success('获取分析报告成功')
    }
    formattedReport.value = '暂无分析报告'
  } catch (error) {
    formattedReport.value = '获取分析报告失败'
    console.error(error)
  }
}

// 删除单条记录
const deleteRecord = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除记录 ${row.id} 吗？`, '提示', {
      type: 'warning'
    })
    const response = await axios.delete(`http://localhost:8181/uploadRecord/delete/${row.id}`, {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      fetchRecords()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('请求失败，请检查后端服务')
    }
  }
}

// 弹窗相关
const dialogVisible = ref(false)
const currentRecord = ref(null)
const formattedReport = ref('')

onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.user-management {
  min-height: 100vh;
}

.box-card {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.query-card .card-header {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title1 {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
}

.action-buttons {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0 0 0;
}

.dialog-row {
  width: 90%;
  display: flex;
  align-items: flex-start;
  margin-bottom: 18px;
}

.dialog-label {
  width: 110px;
  color: #333;
  font-weight: 500;
  text-align: right;
  flex-shrink: 0;
}

.dialog-value {
  flex: 1;
  word-break: break-all;
  min-height: 28px;
  display: flex;
  align-items: center;
}

.dialog-img {
  background: #f5f5f5;
  border: 1px solid #eee;
  width: 180px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep(.el-dialog) {
  min-height: 600px;
}

::v-deep(.el-dialog__body) {
  min-height: 400px;
}

.emo-detail-content {
  width: 100%;
  padding: 10px 0 0 0;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.emo-detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 22px;
  font-size: 15px;
}

.emo-detail-label {
  width: 110px;
  color: #333;
  font-weight: 500;
  text-align: left;
  flex-shrink: 0;
}

.emo-detail-value {
  flex: 1;
  min-height: 28px;
  align-items: center;
  justify-content: flex-start;
}

.emo-img-box {
  background: #f5f5f5;
  border: 1px solid #eee;
  width: 200px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.emo-img-box img {
  max-width: 100%;
  max-height: 100%;
}

.emo-detail-report {
  align-items: flex-start;
}

.emo-json {
  font-family: "Consolas", "Menlo", "Monaco", monospace;
  font-size: 13px;
  background: #fafbfc;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  margin: 0;
  width: 420px;
  max-width: 420px;
  min-height: 180px;
  max-height: 260px;
  overflow: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

.emo-rich-content {
  font-size: 14px;
  background: #fafbfc;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px 12px;
  overflow: auto;
  word-break: break-all;
  line-height: 1.7;
  width: 420px;
  min-height: 420px;
  max-height: 260px;
}

.emo-rich-content h3,
.emo-rich-content h4 {
  margin: 8px 0 4px 0;
  font-weight: bold;
}

.emo-rich-content ul,
.emo-rich-content ol {
  margin: 6px 0 6px 18px;
}

.emo-rich-content p {
  margin: 4px 0;
}

.emo-detail-btn {
  display: flex;
  justify-content: center;
  margin-top: 18px;
}

::v-deep(.el-dialog__header) {
  text-align: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.single-line-img {
  display: flex;
  align-items: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 60px;
}

.data-table-scroll {
  max-height: 520px;
  overflow-y: auto;
  padding-right: 10px;
  padding-left: 10px;
}
</style>
